﻿using System;
using System.Collections.Generic;
using System.Linq;
using LogManager.Base;
using LogManager.Base.Data;
using System.Configuration;

namespace LogManager.Config.Data
{
    /// <summary>
    /// Should not be a singleton
    /// </summary>
    public class ConfigLogService : ILogService
    {        
        private IEnumerable<ILog> _logs;
        private ILogFactory _logFactory;

        /// <summary>
        /// Create a log service that is based on a web configuration file
        /// </summary>
        /// <param name="logCollection">Log collection of the config file</param>
        /// <param name="logFactory"></param>
        public ConfigLogService(LogCollection logCollection,ILogFactory logFactory)
        {
            _logFactory = logFactory;
            _logs = GetLogs(logCollection).AsQueryable();
        }

        private IEnumerable<ILog> GetLogs(LogCollection logCollection)
        {
            foreach (var logConfig in logCollection.Cast<LogConfiguration>())
            {
                //Create log
                var log = _logFactory.Create(logConfig.Type);

                //Map information
                log.Initialize(logConfig.ServerName, logConfig.LogName, logConfig.Type);
                log.Properties["path"] = logConfig.Path;

                yield return log;
            }
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
           //Do nothing
        }

        #endregion

        #region Implementation of ILogService

        public IEnumerable<ILog> All()
        {
            return _logs;
        }

        public IEnumerable<ILog> All(string serverName)
        {
            return _logs.Where(l => l.ServerName == serverName);
        }

        public ILog Get(string serverName, string logName)
        {
            return _logs.Where(l => l.ServerName == serverName && l.LogName == logName).SingleOrDefault();
        }

        #endregion
    }
}